#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //初始化模型设置
    m_modelGrade = new QStandardItemModel(this);
    m_tempModel = new QStandardItemModel(this);
    ui->tableViewGrade->setModel(m_modelGrade);
    m_modelGradeSelection.setModel(m_modelGrade);
    ui->tableViewGrade->setSelectionModel(&m_modelGradeSelection);
    ui->tableViewGrade->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//视图自动拉伸

    //初始化评价模型设置
    m_modelStudentEvalute = new QStandardItemModel(this);
//    ui->tableViewStudentEvalute->setModel(m_modelStudentEvalute);
//    ui->tableViewStudentEvalute->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//视图自动拉伸
    ui->tableViewStudentEvalute->setEditTriggers(QAbstractItemView::NoEditTriggers);//视图不可编辑

    //初始化学生信息模型设置
    m_modelStudent = new QStandardItemModel(this);
    ui->tableViewStudent->setModel(m_modelStudent);
    ui->tableViewStudent->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//视图自动拉伸
    ui->tableViewStudent->setEditTriggers(QAbstractItemView::NoEditTriggers);//视图不可编辑

    //初始化老师信息模型的设置
    m_modelTeacher = new QStandardItemModel(this);
    ui->tableViewTeacher->setModel(m_modelTeacher);
    ui->tableViewTeacher->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//视图自动拉伸
    ui->tableViewTeacher->setEditTriggers(QAbstractItemView::NoEditTriggers);//视图不可编辑

    //初始化课程信息模型的设置
    m_modelClass = new QStandardItemModel(this);
    ui->tableViewClass->setModel(m_modelClass);
    ui->tableViewClass->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//视图自动拉伸
    ui->tableViewClass->setEditTriggers(QAbstractItemView::NoEditTriggers);//视图不可编辑

    //初始化管理界面
    ui->tvClass->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//视图自动拉伸
    ui->tvStudent->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//视图自动拉伸
    ui->tvTeacher->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//视图自动拉伸

    //初始化教师细节界面
    ui->tvTeacherEva->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tvTeacherEva->setEditTriggers(QAbstractItemView::NoEditTriggers);//视图不可编辑

}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_actGetGrade_triggered()
{
    //获取文件路径
    QString filePath = QFileDialog::getOpenFileName(0,"选择文件",QDir::homePath(),"txt(*.txt);;all(*.*)");
    if(QFile::exists(filePath) == false){//如果文件不存在
        QMessageBox::warning(0,"警告","选择文件不存在!");
        return;
    }

    QFile aFile(filePath);
    if(aFile.open(QIODevice::ReadOnly | QIODevice::Text) == false){//如果文件打开失败
        QMessageBox::warning(0,"警告","文件打开失败!");
        return;
    }

    m_modelGrade->clear();//删除原有数据
    ui->combClass->clear();
    ui->combClass->addItem("所有课程");
    ui->combOrder->clear();

    QString tempStr = "";//临时字符串
    for(;!aFile.atEnd();){//读取文件数据
        tempStr = aFile.readLine().simplified();//一行一行地读取数据,删掉首尾所有空格,中间多个空格用一个空格代替
        QStringList tempList;
        if(tempStr.at(0) == '#' && !tempStr.contains("END")){//如果本行是表头
            tempStr.remove('#');//移除#标识符
            tempList = tempStr.split(' ');//按空格分隔字符串,得到表头字符串列表
            m_modelGrade->setColumnCount(tempList.count());

            m_modelGrade->setHorizontalHeaderLabels(tempList);//设置表头
            ui->combOrder->addItems(tempList);
        }
        else if(tempStr.at(0) == '#' && tempStr.contains("END")){//如果是表尾
            break;
        }
        else{//如果是数据

            tempList = tempStr.split(' ');
            QList<QStandardItem*> tempItemList;
            if(ui->combClass->findText(tempList.at(2)) == -1){//如果没有当前课程,则加入这个课程
                ui->combClass->addItem(tempList.at(2));
            }
            for(int i = 0;i < tempList.count(); ++i){
                QStandardItem* aItem = new QStandardItem;
                aItem->setText(tempList.at(i));
                tempItemList.append(aItem);
            }
            m_modelGrade->appendRow(tempItemList);
        }
    }

    ui->combOrderClass->clear();
    ui->combOrderClass->addItem("所有班级");
    ui->combOrderClass->addItems(m_banJiList);

    ui->stackedWidget->setCurrentWidget(ui->pagTeacher);
}


void MainWindow::on_actFIndStudent_triggered()
{
    if(m_modelGrade->rowCount() <= 0){//如果没有导入数据
        QMessageBox::warning(0,"警告","未导入数据!");
        return;
    }


    m_tempModel->removeRows(0,m_tempModel->rowCount());
    m_tempModel->setColumnCount(4);

    if(ui->radioSTundet->isChecked() == true){//如果勾选通过学生姓名学号查找

        QList<QStandardItem*> aitems = m_modelGrade->findItems(ui->editStudent->text(),Qt::MatchExactly,1);//查找所有符合条件的数据项

        if(aitems.count() != 0){//如果有符合条件的项

            for(int i = 0; i < m_modelGrade->rowCount(); ++i){//隐藏所有行
                ui->tableViewGrade->setRowHidden(i,true);
            }

            for(int i = 0;i < aitems.count(); ++i){//显示指定行
                ui->tableViewGrade->setRowHidden(aitems.at(i)->row(),false);

                QList<QStandardItem*> theList;
                for(int j = 0; j < m_modelGrade->columnCount(); ++j){
                    QStandardItem* aitem = new QStandardItem;
                    aitem->setText(this->m_modelGrade->data(this->m_modelGrade->index(aitems.at(i)->row(),j)).toString());
                    theList.append(aitem);
                }

                m_tempModel->appendRow(theList);

            }


            //课程
            QString className = ui->combClass->currentText();
            for(int i = 0;i < m_modelGrade->rowCount(); ++i){//二次加工显示指定行

                if(className == "所有课程"){
                    break;
                }else{
                    if(m_modelGrade->data(m_modelGrade->index(i,2)) != className ){
                        ui->tableViewGrade->setRowHidden(i,true);

                    }
                }

            }

            for(int i = m_tempModel->rowCount() - 1;i >=0;--i){
                if(className == "所有课程"){
                    break;
                }else{
                    if(m_tempModel->data(m_tempModel->index(i,2)) != className){
                        m_tempModel->removeRow(i);
                    }
                }
            }



        }
        else{//如果没有符合条件的项,则显示所有所有行
            QString className = ui->combClass->currentText();

            if(className == "所有课程"){//如果当前为显示所有课程
                for(int i = 0; i < m_modelGrade->rowCount(); ++i){//显示所有行
                    ui->tableViewGrade->setRowHidden(i,false);

                    for(int i = 0;i < this->m_modelGrade->rowCount();++i){

                        QList<QStandardItem*> theList;
                        for(int k = 0;k < m_modelGrade->columnCount();++k){
                            QStandardItem* aitem = new QStandardItem;
                            aitem->setText(this->m_modelGrade->data(this->m_modelGrade->index(i,k)).toString());
                            theList.append(aitem);
                        }
                        m_tempModel->appendRow(theList);
                    }
                }
            }
            else{//如果当前为显示指定课程
                for(int i = 0; i < m_modelGrade->rowCount(); ++i){//显示所有行

                    if(m_modelGrade->data(m_modelGrade->index(i,2)) != className ){
                        ui->tableViewGrade->setRowHidden(i,true);

                    }else{
                        ui->tableViewGrade->setRowHidden(i,false);

                        QList<QStandardItem*> theList;
                        for(int j = 0; j < m_modelGrade->columnCount(); ++j){
                            QStandardItem* aitem = new QStandardItem;
                            aitem->setText(this->m_modelGrade->data(this->m_modelGrade->index(i,j)).toString());
                            theList.append(aitem);

                        }

                        m_tempModel->appendRow(theList);
                    }

                }


            }
        }

    }
    else if(ui->radioGrade->isChecked() == true){//如果勾选通过成绩区间查找
        if(ui->editGradeMin->text().isEmpty() && ui->editGradeMax->text().isEmpty() && ui->combClass->currentText() == "所有课程"){//如果最大最小成绩都为空,并且选择所有课程
            for(int i = 0; i < m_modelGrade->rowCount(); ++i){//显示所有行
                ui->tableViewGrade->setRowHidden(i,false);
            }


            for(int i = 0;i < this->m_modelGrade->rowCount();++i){

                QList<QStandardItem*> theList;
                for(int k = 0;k < m_modelGrade->columnCount();++k){
                    QStandardItem* aitem = new QStandardItem;
                    aitem->setText(this->m_modelGrade->data(this->m_modelGrade->index(i,k)).toString());
                    theList.append(aitem);
                }
                m_tempModel->appendRow(theList);
            }

        }else if(ui->editGradeMin->text().isEmpty() && ui->editGradeMax->text().isEmpty() && ui->combClass->currentText() != "所有课程"){//如果最大最小成绩都为空,但不选择所有课程
            for(int i = 0; i < m_modelGrade->rowCount(); ++i){//隐藏所有行
                ui->tableViewGrade->setRowHidden(i,true);

            }


            for(int i = 0;i < m_modelGrade->rowCount(); ++i){//显示指定行
                QString className = ui->combClass->currentText();
                if(m_modelGrade->data(m_modelGrade->index(i,2)) == className){
                    ui->tableViewGrade->setRowHidden(i,false);

                    QList<QStandardItem*> theList;
                    for(int j = 0; j < m_modelGrade->columnCount(); ++j){
                        QStandardItem* aitem = new QStandardItem;
                        aitem->setText(this->m_modelGrade->data(this->m_modelGrade->index(i,j)).toString());
                        theList.append(aitem);
                    }

                    m_tempModel->appendRow(theList);
                }
            }

        }else if(!ui->editGradeMin->text().isEmpty() || !ui->editGradeMax->text().isEmpty()){//如果最大值或最小值不为空

            int min = ui->editGradeMin->text().toInt();
            int max = ui->editGradeMax->text().toInt();
            if(ui->combClass->currentText() == "所有课程"){//如果查找所有课程在该成绩区间的记录
                for(int i = 0; i < m_modelGrade->rowCount(); ++i){//隐藏所有行
                    ui->tableViewGrade->setRowHidden(i,true);

                }

                for(int i = 0;i < m_modelGrade->rowCount(); ++i){//显示指定行

                    if(m_modelGrade->data(m_modelGrade->index(i,3)).toInt() >= min && m_modelGrade->data(m_modelGrade->index(i,3)).toInt() <= max){
                        ui->tableViewGrade->setRowHidden(i,false);

                        QList<QStandardItem*> theList;
                        for(int j = 0; j < m_modelGrade->columnCount(); ++j){
                            QStandardItem* aitem = new QStandardItem;
                            aitem->setText(this->m_modelGrade->data(this->m_modelGrade->index(i,j)).toString());
                            theList.append(aitem);
                        }

                        m_tempModel->appendRow(theList);
                    }
                }


            }
            else{
                for(int i = 0; i < m_modelGrade->rowCount(); ++i){//隐藏所有行
                    ui->tableViewGrade->setRowHidden(i,true);

                }

                for(int i = 0;i < m_modelGrade->rowCount(); ++i){//显示指定行
                    QString className = ui->combClass->currentText();
                    if(m_modelGrade->data(m_modelGrade->index(i,2)) == className && m_modelGrade->data(m_modelGrade->index(i,3)).toInt() >= min && m_modelGrade->data(m_modelGrade->index(i,3)).toInt() <= max){
                        ui->tableViewGrade->setRowHidden(i,false);

                        QList<QStandardItem*> theList;
                        for(int j = 0; j < m_modelGrade->columnCount(); ++j){
                            QStandardItem* aitem = new QStandardItem;
                            aitem->setText(this->m_modelGrade->data(this->m_modelGrade->index(i,j)).toString());
                            theList.append(aitem);
                        }

                        m_tempModel->appendRow(theList);
                    }
                }
            }

        }

        

    }

    //班级
    QString banjiName = ui->combOrderClass->currentText();

    for(int i = 0;i < m_modelGrade->rowCount();++i){
        if(banjiName == "所有班级"){
            break;
        }
        if(m_modelGrade->index(i,0).isValid() == false){
            continue;
        }
        QList<QStandardItem*> theList = m_modelStudent->findItems(m_modelGrade->data(m_modelGrade->index(i,1)).toString(),Qt::MatchExactly,1);

        if(banjiName != m_modelStudent->data(m_modelStudent->index(theList.first()->row(),2)).toString()){
            ui->tableViewGrade->setRowHidden(i,true);
        }
    }

    for(int i = m_tempModel->rowCount() - 1;i >=0;--i){
        if(banjiName == "所有班级"){
            break;
        }else{
            QList<QStandardItem*> theList = m_modelStudent->findItems(m_tempModel->data(m_tempModel->index(i,1)).toString(),Qt::MatchExactly,1);

            if(m_modelStudent->data(m_modelStudent->index(theList.first()->row(),2)) != banjiName){
                m_tempModel->removeRow(i);
            }
        }
    }

//    QStandardItemModel* theDisplayModel = new QStandardItemModel(this);
//    theDisplayModel->setColumnCount(4);
//    QStringList header;
//    header.append(m_tempModel->headerData(0,Qt::Horizontal).toString());
//    header.append(m_tempModel->headerData(1,Qt::Horizontal).toString());
//    header.append(m_tempModel->headerData(2,Qt::Horizontal).toString());
//    header.append(m_tempModel->headerData(3,Qt::Horizontal).toString());
//    theDisplayModel->setHorizontalHeaderLabels(header);
//    for(int i = 0;i < m_tempModel->rowCount();++i){
//        QList<QStandardItem*> itemList;
//        for(int j = 0; j < m_tempModel->columnCount(); ++j){
//            QStandardItem* item  = new QStandardItem;
//            item->setText(m_tempModel->data(m_tempModel->index(i,j)).toString());
//            itemList.append(item);
//        }
//        theDisplayModel->appendRow(itemList);
//    }

//    ui->tableViewGrade->setModel(theDisplayModel);

    //排序
    Qt::SortOrder order;
    int col = ui->combOrder->currentIndex();
    if(ui->radioAsc->isChecked() == true){//升序
        order = Qt::SortOrder::AscendingOrder;
    }else{//降序
        order = Qt::SortOrder::DescendingOrder;
    }

    ui->tableViewGrade->sortByColumn(col,order);

    //数据统计
    int totalGrade = 0;;
    int count = m_tempModel->rowCount();
    if(count == 0){//如果为空
        ui->labAverageGrade->setText("0");
        ui->labPassRate->setText("0");
        ui->labStandardDev->setText("0");
    }
    int passCount = 0;
    int squareTotal = 0;
    for(int i = 0;i < count; ++i){
        int grade = m_tempModel->data(m_tempModel->index(i,3)).toInt();
        totalGrade += grade;
        if( grade >= 60){
            ++passCount;
        }

    }

    double average = (double)totalGrade / (double)count;

    for(int i = 0;i < count; ++i){
        int grade = m_tempModel->data(m_tempModel->index(i,3)).toInt();
        if(grade > average){
            squareTotal += (grade-average)*(grade-average);
        }else{
            squareTotal += (average-grade)*(average-grade);
        }
    }


    double passRate = (double)passCount / (double)count;
    double standardDec = std::sqrt(squareTotal/(double)count);


    ui->labAverageGrade->setText(QString::asprintf("%.2f",average));
    ui->labPassRate->setText(QString::asprintf("%.2f%%",passRate*100));
    ui->labStandardDev->setText(QString::asprintf("%.2f",standardDec));
}


void MainWindow::on_pushButton_clicked()
{
    ui->actFIndStudent->triggered();
}


void MainWindow::on_actGetStudent_triggered()
{
    //获取文件路径
    QString filePath = QFileDialog::getOpenFileName(0,"选择文件",QDir::homePath(),"txt(*.txt);;all(*.*)");
    if(QFile::exists(filePath) == false){//如果文件不存在
        QMessageBox::warning(0,"警告","选择文件不存在!");
        return;
    }

    QFile aFile(filePath);
    if(aFile.open(QIODevice::ReadOnly | QIODevice::Text) == false){//如果文件打开失败
        QMessageBox::warning(0,"警告","文件打开失败!");
        return;
    }

    m_modelStudent->clear();//删除原有数据
    m_studentList.clear();

    QString tempStr = "";//临时字符串
    for(;!aFile.atEnd();){//读取文件数据
        tempStr = aFile.readLine().simplified();//一行一行地读取数据,删掉首尾所有空格,中间多个空格用一个空格代替
        QStringList tempList;
        if(tempStr.at(0) == '#' && !tempStr.contains("END")){//如果本行是表头
            tempStr.remove('#');//移除#标识符
            tempList = tempStr.split(' ');//按空格分隔字符串,得到表头字符串列表
            m_modelStudent->setColumnCount(tempList.count());

            m_modelStudent->setHorizontalHeaderLabels(tempList);//设置表头

        }
        else if(tempStr.at(0) == '#' && tempStr.contains("END")){//如果是表尾
            break;
        }
        else{//如果是数据

            tempList = tempStr.split(' ');
            QList<QStandardItem*> tempItemList;

            for(int i = 0;i < tempList.count(); ++i){
                QStandardItem* aItem = new QStandardItem;
                aItem->setText(tempList.at(i));
                tempItemList.append(aItem);
            }
            m_modelStudent->appendRow(tempItemList);

            //记录学生列表
            if(!m_studentList.contains(tempList.at(1))){
                m_studentList.append(tempList.at(1));
            }

            //记录班级列表
            if(!m_banJiList.contains(tempList.at(2))){
                m_banJiList.append(tempList.at(2));
            }

        }
    }

    ui->stackedWidget->setCurrentWidget(ui->pagStudent);
}


void MainWindow::on_actStuudentEvalute_triggered()
{
    //获取文件路径
    QString filePath = QFileDialog::getOpenFileName(0,"选择文件",QDir::homePath(),"txt(*.txt);;all(*.*)");
    if(QFile::exists(filePath) == false){//如果文件不存在
        QMessageBox::warning(0,"警告","选择文件不存在!");
        return;
    }

    QFile aFile(filePath);
    if(aFile.open(QIODevice::ReadOnly | QIODevice::Text) == false){//如果文件打开失败
        QMessageBox::warning(0,"警告","文件打开失败!");
        return;
    }

    m_modelStudentEvalute->clear();//删除原有数据

    QString tempStr = "";//临时字符串
    for(;!aFile.atEnd();){//读取文件数据
        tempStr = aFile.readLine().simplified();//一行一行地读取数据,删掉首尾所有空格,中间多个空格用一个空格代替
        QStringList tempList;
        if(tempStr.at(0) == '#' && !tempStr.contains("END")){//如果本行是表头
            tempStr.remove('#');//移除#标识符
            tempList = tempStr.split(' ');//按空格分隔字符串,得到表头字符串列表
            m_modelStudentEvalute->setColumnCount(tempList.count());

            m_modelStudentEvalute->setHorizontalHeaderLabels(tempList);//设置表头

        }
        else if(tempStr.at(0) == '#' && tempStr.contains("END")){//如果是表尾
            break;
        }
        else{//如果是数据

            tempList = tempStr.split(' ');
            QList<QStandardItem*> tempItemList;

            for(int i = 0;i < tempList.count(); ++i){
                QStandardItem* aItem = new QStandardItem;
                aItem->setText(tempList.at(i));
                tempItemList.append(aItem);
            }
            m_modelStudentEvalute->appendRow(tempItemList);
        }
    }

//    ui->tableViewStudentEvalute->sortByColumn(2);

    //初始化教师排名界面
    QList<double> teacherScore;
    QList<int> teacherEvaCOunt;
    QList<int> teacherEvaTotal;
    double totalScore = 0;
    int count = 0;
    for(int i = 0;i < m_teacherList.count(); ++i){
        for(int j = 0;j < m_modelStudentEvalute->rowCount(); ++j){
            if(m_teacherList.at(i) == m_modelStudentEvalute->data(m_modelStudentEvalute->index(j,0)).toString()){
                totalScore += m_modelStudentEvalute->data(m_modelStudentEvalute->index(j,3)).toDouble();
                ++count;
            }
        }
        teacherScore.append(totalScore/(double)count);
        teacherEvaCOunt.append(count);
        teacherEvaTotal.append(totalScore);
        totalScore = 0;
        count = 0;
    }

    QStandardItemModel* theModel = new QStandardItemModel(this);
    theModel->setColumnCount(4);
    theModel->setHeaderData(0,Qt::Horizontal,"教师");
    theModel->setHeaderData(1,Qt::Horizontal,"评价人数");
    theModel->setHeaderData(2,Qt::Horizontal,"总分");
    theModel->setHeaderData(3,Qt::Horizontal,"平均分");


    for(int i = 0; i < m_teacherList.count();++i){
        QList<QStandardItem*> theItemList;

        QStandardItem* item0 = new QStandardItem;
        item0->setText(m_teacherList.at(i));
        theItemList.append(item0);

        QStandardItem* item1 = new QStandardItem;
        item1->setText(QString::asprintf("%d",teacherEvaCOunt.at(i)));
        theItemList.append(item1);

        QStandardItem* item2 = new QStandardItem;
        item2->setText(QString::asprintf("%d",teacherEvaTotal.at(i)));
        theItemList.append(item2);

        QStandardItem* item3 = new QStandardItem;
        item3->setText(QString::asprintf("%.2f",teacherScore.at(i)));
        theItemList.append(item3);

        theModel->appendRow(theItemList);

    }

    ui->tableViewStudentEvalute->setModel(theModel);
    ui->tableViewStudentEvalute->sortByColumn(3,Qt::DescendingOrder);

    ui->stackedWidget->setCurrentWidget(ui->pagTeacherEvalute);
}


void MainWindow::on_actTeacher_triggered()
{
    ui->stackedWidget->setCurrentWidget(ui->pagTeacher2);
}


void MainWindow::on_actStudent_triggered()
{
    ui->stackedWidget->setCurrentWidget(ui->pagStudent);
}


void MainWindow::on_tableViewStudent_doubleClicked(const QModelIndex &index)
{
    //清理原有数据
    ui->editEvalutaionMessage->clear();
    ui->combEvaTeacher->clear();
    ui->combTeacherClass->clear();
    ui->spinBoxEvaGrade->setValue(60);

    //获取学生基本信息
    QString id = m_modelStudent->item(index.row(),0)->text();
    m_curStuName = m_modelStudent->item(index.row(),1)->text();
    QString stuClass = m_modelStudent->item(index.row(),2)->text();
    QString stuMajor = m_modelStudent->item(index.row(),3)->text();

    //设置界面信息
    ui->labStuId->setText(id);
    ui->labStuName->setText(m_curStuName);
    ui->labStuClass->setText(stuClass);
    ui->labStuMajor->setText(stuMajor);

    ui->combClassStu->clear();
    ui->combEvaTeacher->clear();
//    ui->combClassStu->addItems(m_classList);
    ui->combEvaTeacher->addItems(m_teacherList);

//    //课程列表
//    for(int i = 0;i < m_modelTeacher->rowCount();++i){
//        if(m_modelTeacher->data(m_modelTeacher->index(i,1)).toString() == ui->combEvaTeacher->currentText()){
//            for(int j = 2; j < m_modelTeacher->columnCount(); ++j){
//                if(!(m_modelTeacher->item(i,j) == NULL) &&  !m_modelTeacher->data(m_modelTeacher->index(i,j)).toString().isEmpty()){

//                    ui->combTeacherClass->addItem(m_modelTeacher->data(m_modelTeacher->index(i,j)).toString());
//                }
//            }
//            break;
//        }
//    }

    //设置表格信息
    QStringList headers;
    headers.append("课程");
    headers.append("成绩");
    headers.append("学分");
    QStandardItemModel* theModel = new QStandardItemModel(this);
    ui->tableViewStudentGrade->setModel(theModel);
    ui->tableViewStudentGrade->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//视图自动拉伸
    ui->tableViewStudentGrade->setEditTriggers(QAbstractItemView::NoEditTriggers);//视图不可编辑
    theModel->setColumnCount(3);
    theModel->setHorizontalHeaderLabels(headers);

    //添加同名学生成绩
    for(int i = 0;i < m_modelGrade->rowCount();++i){
        if(m_curStuName == m_modelGrade->data(m_modelGrade->index(i,1))){
            QList<QStandardItem*> tempList;
            for(int j = 2;j < 4; ++j){
                QStandardItem* item = new QStandardItem;
                item->setText(m_modelGrade->data(m_modelGrade->index(i,j)).toString());
                tempList.append(item);
            }

            for(int i = 0;i < m_modelClass->rowCount() ; ++i){
                if(m_modelClass->data(m_modelClass->index(i,1)).toString() == tempList.at(0)->text()){
                    QStandardItem* item = new QStandardItem;
                    item->setText(m_modelClass->data(m_modelClass->index(i,2)).toString());
                    tempList.append(item);
                    break;
                }
            }


            theModel->appendRow(tempList);
        }
    }


    //设置选课界面信息
    QStringList headers2;
    headers2.append("课程编号");
    headers2.append("课程名称");
    headers2.append("学分");
    headers2.append("学时");
    QStandardItemModel* theModel2 = new QStandardItemModel(this);
//    ui->tableViewChoicedClass->setModel(theModel2);
    ui->tableViewChoicedClass->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//视图自动拉伸
    ui->tableViewChoicedClass->setEditTriggers(QAbstractItemView::NoEditTriggers);//视图不可编辑
    theModel2->setColumnCount(4);
    theModel2->setHorizontalHeaderLabels(headers2);

    for(int i = 0;i < m_modelClass->rowCount();++i){
        if("选修" == m_modelClass->data(m_modelClass->index(i,4))){
            QList<QStandardItem*> tempList;
            for(int j = 0;j < 4; ++j){
                QStandardItem* item = new QStandardItem;
                item->setText(m_modelClass->data(m_modelClass->index(i,j)).toString());
                tempList.append(item);
            }
            theModel2->appendRow(tempList);
        }
    }

    //计算当前学分
    double totalPoint = 0;
    for(int i = 0;i < theModel->rowCount(); ++i){

        if(theModel->data(theModel->index(i,1)).toInt() >= 60){
            totalPoint += theModel->data(theModel->index(i,2)).toDouble();
        }
    }
    ui->labTotalPoint->setText(QString::asprintf("%.2f",totalPoint));

    //选课
    QStringList choiceClassList;
    for(int i = theModel2->rowCount() - 1;i >= 0; --i){
        bool ok = false;
        for(int j = 0; j < theModel->rowCount(); ++j){
            if(theModel2->data(theModel2->index(i,1)) == theModel->data(theModel->index(j,0))){
                ok = true;
                break;
            }
        }
        if(ok == false){
            choiceClassList.append(theModel2->data(theModel2->index(i,1)).toString());
            theModel2->removeRow(i);
        }
    }

    ui->combClassStu->addItems(choiceClassList);
    ui->tableViewChoicedClass->setModel(theModel2);




    ui->stackedWidget->setCurrentWidget(ui->pagStudentDetail);
}


void MainWindow::on_actGrade_triggered()
{
    ui->stackedWidget->setCurrentWidget(ui->pagTeacher);
}


void MainWindow::on_actGetTeacher_triggered()
{
    //获取文件路径
    QString filePath = QFileDialog::getOpenFileName(0,"选择文件",QDir::homePath(),"txt(*.txt);;all(*.*)");
    if(QFile::exists(filePath) == false){//如果文件不存在
        QMessageBox::warning(0,"警告","选择文件不存在!");
        return;
    }

    QFile aFile(filePath);
    if(aFile.open(QIODevice::ReadOnly | QIODevice::Text) == false){//如果文件打开失败
        QMessageBox::warning(0,"警告","文件打开失败!");
        return;
    }

    m_modelTeacher->clear();//删除原有数据
    m_teacherList.clear();

    QString tempStr = "";//临时字符串
    for(;!aFile.atEnd();){//读取文件数据
        tempStr = aFile.readLine().simplified();//一行一行地读取数据,删掉首尾所有空格,中间多个空格用一个空格代替
        QStringList tempList;
        if(tempStr.at(0) == '#' && !tempStr.contains("END")){//如果本行是表头
            tempStr.remove('#');//移除#标识符
            tempList = tempStr.split(' ');//按空格分隔字符串,得到表头字符串列表
            m_modelTeacher->setColumnCount(tempList.count());

            m_modelTeacher->setHorizontalHeaderLabels(tempList);//设置表头

        }
        else if(tempStr.at(0) == '#' && tempStr.contains("END")){//如果是表尾
            break;
        }
        else{//如果是数据

            tempList = tempStr.split(' ');
            QList<QStandardItem*> tempItemList;

            for(int i = 0;i < tempList.count(); ++i){
                QStandardItem* aItem = new QStandardItem;
                aItem->setText(tempList.at(i));
                tempItemList.append(aItem);
            }
            m_modelTeacher->appendRow(tempItemList);

            //添加老师列表
            if(!m_teacherList.contains(tempList.at(1))){
                m_teacherList.append(tempList.at(1));
            }
        }
    }



    ui->stackedWidget->setCurrentWidget(ui->pagTeacher2);
}


void MainWindow::on_actGetClass_triggered()
{
    //获取文件路径
    QString filePath = QFileDialog::getOpenFileName(0,"选择文件",QDir::homePath(),"txt(*.txt);;all(*.*)");
    if(QFile::exists(filePath) == false){//如果文件不存在
        QMessageBox::warning(0,"警告","选择文件不存在!");
        return;
    }

    QFile aFile(filePath);
    if(aFile.open(QIODevice::ReadOnly | QIODevice::Text) == false){//如果文件打开失败
        QMessageBox::warning(0,"警告","文件打开失败!");
        return;
    }

    m_modelClass->clear();//删除原有数据
    m_classList.clear();

    QString tempStr = "";//临时字符串
    for(;!aFile.atEnd();){//读取文件数据
        tempStr = aFile.readLine().simplified();//一行一行地读取数据,删掉首尾所有空格,中间多个空格用一个空格代替
        QStringList tempList;
        if(tempStr.at(0) == '#' && !tempStr.contains("END")){//如果本行是表头
            tempStr.remove('#');//移除#标识符
            tempList = tempStr.split(' ');//按空格分隔字符串,得到表头字符串列表
            m_modelClass->setColumnCount(tempList.count());

            m_modelClass->setHorizontalHeaderLabels(tempList);//设置表头

        }
        else if(tempStr.at(0) == '#' && tempStr.contains("END")){//如果是表尾
            break;
        }
        else{//如果是数据

            tempList = tempStr.split(' ');
            QList<QStandardItem*> tempItemList;

            for(int i = 0;i < tempList.count(); ++i){
                QStandardItem* aItem = new QStandardItem;
                aItem->setText(tempList.at(i));
                tempItemList.append(aItem);
            }
            m_modelClass->appendRow(tempItemList);

            //添加课程列表
            if(!m_classList.contains(tempList.at(1))){
                m_classList.append(tempList.at(1));
            }
        }
    }



    ui->stackedWidget->setCurrentWidget(ui->pagClass);
}


void MainWindow::on_actClass_triggered()
{
    ui->stackedWidget->setCurrentWidget(ui->pagClass);
}


void MainWindow::on_btnChoiceClass_clicked()
{
    QStandardItemModel* theModel = (QStandardItemModel*)ui->tableViewChoicedClass->model();

    //检查是已经包含本门课程
    for(int i = 0;i < theModel->rowCount(); ++i){
        if(theModel->data(theModel->index(i,1)).toString() == ui->combClassStu->currentText()){
            return;
        }
    }

    QList<QStandardItem*> theList;
    QList<QStandardItem*> theList2 = m_modelClass->findItems(ui->combClassStu->currentText().simplified(),Qt::MatchFlag::MatchExactly,1);


    for(int j = 0;j < m_modelClass->columnCount() - 1; ++j){
        QStandardItem* item = new QStandardItem;
        item->setText(m_modelClass->data(m_modelClass->index(theList2.first()->row(),j)).toString());
        theList.append(item);
    }

    theModel->appendRow(theList);
}


void MainWindow::on_btnLoseClass_clicked()
{
    QStandardItemModel* theModel = (QStandardItemModel*)ui->tableViewChoicedClass->model();

    //检查是已经包含本门课程
    for(int i = 0;i < theModel->rowCount(); ++i){
        if(theModel->data(theModel->index(i,1)).toString() == ui->combClassStu->currentText()){
            theModel->removeRow(i);
            return;
        }
    }
}


void MainWindow::on_actTeacherEva_triggered()
{
    //初始化教师排名界面
    QList<double> teacherScore;
    QList<int> teacherEvaCOunt;
    QList<int> teacherEvaTotal;
    double totalScore = 0;
    int count = 0;
    for(int i = 0;i < m_teacherList.count(); ++i){
        for(int j = 0;j < m_modelStudentEvalute->rowCount(); ++j){
            if(m_teacherList.at(i) == m_modelStudentEvalute->data(m_modelStudentEvalute->index(j,0)).toString()){
                totalScore += m_modelStudentEvalute->data(m_modelStudentEvalute->index(j,3)).toDouble();
                ++count;
            }
        }
        teacherScore.append(totalScore/(double)count);
        teacherEvaCOunt.append(count);
        teacherEvaTotal.append(totalScore);
        totalScore = 0;
        count = 0;
    }

    QStandardItemModel* theModel = new QStandardItemModel(this);
    theModel->setColumnCount(4);
    theModel->setHeaderData(0,Qt::Horizontal,"教师");
    theModel->setHeaderData(1,Qt::Horizontal,"评价人数");
    theModel->setHeaderData(2,Qt::Horizontal,"总分");
    theModel->setHeaderData(3,Qt::Horizontal,"平均分");


    for(int i = 0; i < m_teacherList.count();++i){
        QList<QStandardItem*> theItemList;

        QStandardItem* item0 = new QStandardItem;
        item0->setText(m_teacherList.at(i));
        theItemList.append(item0);

        QStandardItem* item1 = new QStandardItem;
        item1->setText(QString::asprintf("%d",teacherEvaCOunt.at(i)));
        theItemList.append(item1);

        QStandardItem* item2 = new QStandardItem;
        item2->setText(QString::asprintf("%d",teacherEvaTotal.at(i)));
        theItemList.append(item2);

        QStandardItem* item3 = new QStandardItem;
        item3->setText(QString::asprintf("%.2f",teacherScore.at(i)));
        theItemList.append(item3);

        theModel->appendRow(theItemList);

    }

    ui->tableViewStudentEvalute->setModel(theModel);
    ui->tableViewStudentEvalute->sortByColumn(3,Qt::DescendingOrder);
    ui->stackedWidget->setCurrentWidget(ui->pagTeacherEvalute);
}



void MainWindow::on_pushButton_4_clicked()
{
    QList<QStandardItem*> theList;

    //获取评价老师名字
    QStandardItem* item0 = new QStandardItem;
    item0->setText(ui->combEvaTeacher->currentText());
    theList.append(item0);

    //获取评价课程名字
    QStandardItem* item05 = new QStandardItem;
    item05->setText(ui->combTeacherClass->currentText());
    theList.append(item05);

    //获取评价学生名字
    QStandardItem* item1 = new QStandardItem;
    item1->setText(m_curStuName);
    theList.append(item1);

    //获取评价分数
    QStandardItem* item2 = new QStandardItem;
    item2->setText(QString::asprintf("%d",ui->spinBoxEvaGrade->value()));
    theList.append(item2);

    //获取评语
    QStandardItem* item3 = new QStandardItem;
    item3->setText(ui->editEvalutaionMessage->text());
    theList.append(item3);

    m_modelStudentEvalute->appendRow(theList);
    m_modelStudentEvalute->sort(3,Qt::DescendingOrder);
    QMessageBox::information(0,"提示","评价成功!");

}


void MainWindow::on_actSysMange_triggered()
{
    ui->tvTeacher->setModel(m_modelTeacher);
    ui->tvClass->setModel(m_modelClass);
    ui->tvStudent->setModel(m_modelStudent);

    ui->stackedWidget->setCurrentWidget(ui->pagManage);
}


void MainWindow::on_btnAppendTeacher_clicked()
{
    QList<QStandardItem*> theList;
    for(int i = 0 ;i < m_modelTeacher->columnCount();++i){
        QStandardItem* item = new QStandardItem;
        item->setText("");
        theList.append(item);
    }
    m_modelTeacher->appendRow(theList);
}


void MainWindow::on_btnAppendStudent_clicked()
{
    QList<QStandardItem*> theList;
    for(int i = 0 ;i < m_modelStudent->columnCount();++i){
        QStandardItem* item = new QStandardItem;
        item->setText("");
        theList.append(item);
    }
    m_modelStudent->appendRow(theList);
}


void MainWindow::on_btnAppendClass_clicked()
{
    QList<QStandardItem*> theList;
    for(int i = 0 ;i < m_modelClass->columnCount();++i){
        QStandardItem* item = new QStandardItem;
        item->setText("");
        theList.append(item);
    }
    m_modelClass->appendRow(theList);
}


void MainWindow::on_tvTeacher_doubleClicked(const QModelIndex &index)
{
    int result = QMessageBox::warning(0,"提示","确定删除该成员信息?",QMessageBox::Ok | QMessageBox::Cancel,QMessageBox::Cancel);
    if(result == QMessageBox::Ok){
        m_modelTeacher->removeRow(index.row());
    }
}


void MainWindow::on_tvStudent_doubleClicked(const QModelIndex &index)
{
    int result = QMessageBox::warning(0,"提示","确定删除该学生信息?",QMessageBox::Ok | QMessageBox::Cancel,QMessageBox::Cancel);
    if(result == QMessageBox::Ok){
        m_modelStudent->removeRow(index.row());
    }
}


void MainWindow::on_tvClass_doubleClicked(const QModelIndex &index)
{
    int result = QMessageBox::warning(0,"提示","确定删除该课程信息?",QMessageBox::Ok | QMessageBox::Cancel,QMessageBox::Cancel);
    if(result == QMessageBox::Ok){
        m_modelClass->removeRow(index.row());
    }
}


void MainWindow::on_actSaveFile_triggered()
{
    QString path = "none";
    path = QFileDialog::getExistingDirectory(0,"选择目录",QDir::homePath());//选择目录
    if(path == "none"){//如果没选择成功
        return;
    }

    QString score = path + "/score.txt";
    QString student = path + "/student.txt";
    QString teacher = path + "/staff.txt";
    QString classStu = path + "/module.txt";
    QString stuEva = path + "/studentEvaluation.txt";

    QFile scoreFile(score);
    QFile studentFile(student);
    QFile teacherFile(teacher);
    QFile classStuFile(classStu);
    QFile stuEvaFile(stuEva);

    scoreFile.open(QIODevice::WriteOnly|QIODevice::Text);
    studentFile.open(QIODevice::WriteOnly|QIODevice::Text);
    teacherFile.open(QIODevice::WriteOnly|QIODevice::Text);
    classStuFile.open(QIODevice::WriteOnly|QIODevice::Text);
    stuEvaFile.open(QIODevice::WriteOnly|QIODevice::Text);

    QTextStream scoreStream(&scoreFile);
    QTextStream studentStream(&studentFile);
    QTextStream teacherStream(&teacherFile);
    QTextStream classStuStream(&classStuFile);
    QTextStream stuEvaStream(&stuEvaFile);

    //保存成绩文件
    QString str = "";
    str +="#";
    for(int i = 0;i < m_modelGrade->columnCount();++i){
        str += m_modelGrade->headerData(i,Qt::Horizontal).toString();
        str += ' ';
    }
    str +='\n';
    scoreStream << str;
    str = "";
    for(int i = 0;i < m_modelGrade->rowCount();++i){
        for(int j = 0;j < m_modelGrade->columnCount();++j ){
            str += m_modelGrade->data(m_modelGrade->index(i,j)).toString();
            str += ' ';
        }
        str += '\n';
        scoreStream << str;
        str = "";
    }
    str = "#END";
    scoreStream << str;
    scoreFile.close();

    //保存老师文件
    str = "";
    str +="#";
    for(int i = 0;i < m_modelTeacher->columnCount();++i){
        str += m_modelTeacher->headerData(i,Qt::Horizontal).toString();
        str += ' ';
    }
    str +='\n';
    teacherStream << str;
    str = "";
    for(int i = 0;i < m_modelTeacher->rowCount();++i){
        for(int j = 0;j < m_modelTeacher->columnCount();++j ){
            str += m_modelTeacher->data(m_modelTeacher->index(i,j)).toString();
            str += ' ';
        }
        str += '\n';
        teacherStream << str;
        str = "";
    }
    str = "#END";
    teacherStream << str;
    teacherFile.close();

    //保存学生文件
    str = "";
    str +="#";
    for(int i = 0;i < m_modelStudent->columnCount();++i){
        str += m_modelStudent->headerData(i,Qt::Horizontal).toString();
        str += ' ';
    }
    str +='\n';
    studentStream << str;
    str = "";
    for(int i = 0;i < m_modelStudent->rowCount();++i){
        for(int j = 0;j < m_modelStudent->columnCount();++j ){
            str += m_modelStudent->data(m_modelStudent->index(i,j)).toString();
            str += ' ';
        }
        str += '\n';
        studentStream << str;
        str = "";
    }
    str = "#END";
    studentStream << str;
    studentFile.close();

    //保存课程文件
    str = "";
    str +="#";
    for(int i = 0;i < m_modelClass->columnCount();++i){
        str += m_modelClass->headerData(i,Qt::Horizontal).toString();
        str += ' ';
    }
    str +='\n';
    classStuStream << str;
    str = "";
    for(int i = 0;i < m_modelClass->rowCount();++i){
        for(int j = 0;j < m_modelClass->columnCount();++j ){
            str += m_modelClass->data(m_modelClass->index(i,j)).toString();
            str += ' ';
        }
        str += '\n';
        classStuStream << str;
        str = "";
    }
    str = "#END";
    classStuStream << str;
    classStuFile.close();

    //保存评价文件
    str = "";
    str +="#";
    for(int i = 0;i < m_modelStudentEvalute->columnCount();++i){
        str += m_modelStudentEvalute->headerData(i,Qt::Horizontal).toString();
        str += ' ';
    }
    str +='\n';
    stuEvaStream << str;
    str = "";
    for(int i = 0;i < m_modelStudentEvalute->rowCount();++i){
        for(int j = 0;j < m_modelStudentEvalute->columnCount();++j ){
            str += m_modelStudentEvalute->data(m_modelStudentEvalute->index(i,j)).toString();
            str += ' ';
        }
        str += '\n';
        stuEvaStream << str;
        str = "";
    }
    str = "#END";
    stuEvaStream << str;
    stuEvaFile.close();

}


void MainWindow::on_pushButton_2_clicked()
{
    ui->combOrderClass->clear();
    ui->combOrderClass->addItem("所有班级");
    ui->combOrderClass->addItems(m_banJiList);
    ui->stackedWidget->setCurrentWidget(ui->pagTeacher);
}


void MainWindow::on_tableViewTeacher_doubleClicked(const QModelIndex &index)
{
    m_curTeacherName = m_modelTeacher->data(m_modelTeacher->index(index.row(),1)).toString();

    ui->labTeacherName->setText(m_curTeacherName);
    ui->labTeacherId->setText(m_modelTeacher->data(m_modelTeacher->index(index.row(),0)).toString());

    QStandardItemModel* theModel = new QStandardItemModel(this);
    QStringList header;
    QList<QStandardItem*> theList;
    for(int i = 0;i < m_modelStudentEvalute->columnCount(); ++i){
//        QStandardItem* item = new QStandardItem;
//        item->setText(m_modelStudentEvalute->headerData(i,Qt::Horizontal).toString());
//        theList.append(item);
        header.append(m_modelStudentEvalute->headerData(i,Qt::Horizontal).toString());
    }
    theModel->setHorizontalHeaderLabels(header);


    double totalScore = 0;
    int count = 0;
    for(int i = 0;i < m_modelStudentEvalute->rowCount(); ++i){
        if(m_modelStudentEvalute->data(m_modelStudentEvalute->index(i,0)).toString() == m_curTeacherName){
            totalScore += m_modelStudentEvalute->data(m_modelStudentEvalute->index(i,3)).toDouble();
            ++count;

            for(int j = 0;j < m_modelStudentEvalute->columnCount(); ++j){
                QStandardItem* item = new QStandardItem;
                item->setText(m_modelStudentEvalute->data(m_modelStudentEvalute->index(i,j)).toString());
                theList.append(item);

            }

            theModel->appendRow(theList);
            theList.clear();
        }
    }
    ui->tvTeacherEva->setModel(theModel);
    ui->tvTeacherEva->sortByColumn(3,Qt::DescendingOrder);
    ui->labTeacherAverageScore->setText(QString::asprintf("%.2f",totalScore/(double)count));

    ui->stackedWidget->setCurrentWidget(ui->pagTeacher2Detail);

}


void MainWindow::on_combEvaTeacher_currentTextChanged(const QString &arg1)
{
    ui->combTeacherClass->clear();

    for(int i = 0;i < m_modelTeacher->rowCount();++i){
        if(m_modelTeacher->data(m_modelTeacher->index(i,1)).toString() == ui->combEvaTeacher->currentText()){
            for(int j = 2; j < m_modelTeacher->columnCount(); ++j){
                if(!(m_modelTeacher->item(i,j) == NULL)  &&  !m_modelTeacher->data(m_modelTeacher->index(i,j)).toString().isEmpty()){

                    ui->combTeacherClass->addItem(m_modelTeacher->data(m_modelTeacher->index(i,j)).toString());
                }
            }
            break;
        }
    }
}


void MainWindow::on_combEvaTeacher_currentIndexChanged(int index)
{

}

